import { merge, random } from "lodash";
import Sortable from "sortablejs";
export default {
    data() {
        return {
            colSortable: null,
            rowSortable: null
        }
    },
    methods: {
        /**
         * 底部合计
         * @param {*} param0
         * @returns
         */
        getSummaries(tableColumns, { columns, data }) {// 底部统计
            return columns.map((column, columnIndex) => {
                if (columnIndex === 0) {
                    return $AONE_LAN.sum
                }
                const tableColumn = tableColumns.find(it => it.props.prop == column.property)
                if (column.property && tableColumn?.props?.summary) {
                    if(!data.find(it=>it[column.property]!='--')) return '--'
                    const values = data.map(item => Number(item[column.property]));
                    const sum = values.reduce((prev, curr) => {
                        const value = isNaN(curr) ? 0 : Number(curr);
                        return prev + value;
                    }, 0);
                    return tableColumn?.props?.integer ? parseInt(sum) : this.$tool.formatNum(sum, true)
                }
                return ''
            })
        },
        /**
         * 添加特殊类
         * @param {*} param0
         * @returns
         */
        rowClassName({ row, rowIndex }) {
            return null
        },
        /**
         * 排序列
         * @param {*} param0
         */
        sortChange({ prop, order }) {
            if (order) {
                this.sort.orderFiledName = prop
                this.sort.orderFiledAsc = order
            }
            else {
                this.sort.orderFiledName = ""
                this.sort.orderFiledAsc = ""
            }
            this.reload()
        },
        /**
         * 单条选中/取消
         * @param {*} param0
         */
        selectionChange(rows) {
            this.selectedRows = rows
        },
        /**
         * 翻页
         * @param {*} value
         */
        pageChange(value) {
            this.axiosConfig.currentPage = value.currentPage
            this.axiosConfig.currentPageTotal = value.pageSize
            this.reload()
        },

        renderGuangBiao() {
            return (
                <div>
                    <div
                        class="gundong_left gundong_icon"
                        onClick={() => this.gundong("left")}
                    >
                        <img v-src="zou.png" alt="" />
                    </div>
                    <div
                        class="gundong_right gundong_icon"
                        onClick={() => this.gundong("right")}
                    >
                        <img v-src="zou.png" alt="" />
                    </div>
                </div>
            );
        },
        // 列表滚动
        gundong(data) {
            var num = 1;
            if (data == "right") {
                var times = setInterval((res) => {
                    num++;
                    if (num == 50) {
                        clearTimeout(times);
                        return;
                    }
                    document.getElementsByClassName(
                        "el-table__body-wrapper"
                    )[0].scrollLeft += 4;
                }, 5);
            } else {
                var times = setInterval((res) => {
                    num++;
                    if (num == 50) {
                        clearTimeout(times);
                        return;
                    }
                    document.getElementsByClassName(
                        "el-table__body-wrapper"
                    )[0].scrollLeft -= 4;
                }, 5);
            }
        },
        buildProps() {
            const tableProps = {}
            return merge(tableProps, this.mergeTableOptionsSync.tableProps)
        },
        calcTableHeight() {
            // 计算当前页表格占一屏高度
            if (this.mergeTableOptionsSync.useVirtual) {
                const aonePageHeight = document.querySelector('.aone-page').clientHeight
                const aoneHeaderHeight = document.querySelector('.aone-page-header')?.clientHeight || 0
                const aoneSearchHeight = document.querySelector('.aone-page-search')?.clientHeight || 0
                const aonePaggerHeight = (document.querySelector('.aone-table-pagger')?.clientHeight || 0) + 20
                this.tableHeight = aonePageHeight - aoneHeaderHeight - aoneSearchHeight - aonePaggerHeight
            }
            // 外部没传 rowHeight 就自动计算，随机取一些行计算最大高度
            if (this.mergeTableOptionsSync.useVirtual && !this.tableOptions.rowHeight && this.tableData.items.length > 0) {
                const tableRows = document.querySelectorAll('.el-table__body-wrapper .el-table__row')
                const max = tableRows.length - 1
                const rowArr = Array.from({ length: 5 }).map(_ => {
                    const index = random(0, max);
                    return tableRows[index];
                });
                const rowHeight = [...rowArr].reduce((p, row) => {
                    const h = row?.clientHeight || 0;
                    return Math.max(h, p)
                }, 0);
                if (rowHeight) {
                    this.rowHeight = rowHeight;
                }
            }
        },

        //列拖拽
        columnDrop() {
            this.$nextTick(() => {
                let xTable = this.$refs.xTable;
                if(!xTable) return
                const that = this
                this.colSortable = Sortable.create(
                    xTable.$el.querySelector(
                        ".el-table__header-wrapper thead tr"
                    ),
                    {
                        handle: "th",
                        onEnd: ({ item, newIndex, oldIndex }) => {
                            const fullColumn = xTable.getTableColumn();
                            let targetThElem = item;
                            let wrapperElem = targetThElem.parentNode;
                            let newColumn = fullColumn[newIndex];
                            // 移动到目标列
                            let currRow = fullColumn.splice(oldIndex, 1)[0];
                            fullColumn.splice(newIndex, 0, currRow);
                            that.$nextTick(() => {
                                xTable.doLayout();
                            })
                        },
                    }
                );
            });
        },
        rowDrop() {
            this.$nextTick(() => {
                if (!this.mergeTableOptionsSync.sortApiPromise) return;
                let xTable = this.$refs.xTable;
                if(!xTable) return
                this.rowSortable = Sortable.create(
                    xTable.$el.querySelector(".el-table__body-wrapper tbody"),
                    {
                        handle: ".el-table__row",
                        onEnd: async ({ newIndex, oldIndex }) => {
                            var old = this.tableData.items[oldIndex]; //排序的数据
                            var Snew = this.tableData.items[newIndex]; //替换的数据
                            var sorts =
                                old.id + "_" + Snew.order + "," + Snew.id + "_" + old.order;
                            if (oldIndex != newIndex) {
                                await this.mergeTableOptionsSync.sortApiPromise({ sorts: sorts })
                                this.$alert({ center: res.message, type: "success" });
                                let currRow = this.tableData.items.splice(oldIndex, 1)[0];
                                this.tableData.items.splice(newIndex, 0, currRow);
                            }
                        },
                    }
                );
            });
        }
    },
    mounted() {
        this.columnDrop()
        this.rowDrop()
    },
    beforeDestroy() {
        if (this.colSortable) {
            this.colSortable.destroy();
        }
        if (this.rowSortable) {
            this.rowSortable.destroy();
        }
    }
}
